#!/usr/bin/env python
# coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
###############################################
from gui.dict_app import dict_app
from modules.baidu.baidu import d_baidu
from gui.lang import get_default_lang
import gettext
gettext.install('lang', './locale', unicode=False)
try:
        gettext.translation('lang', './locale', languages=[get_default_lang()]).install(True)
except IOError,e:
        #print e
        pass
from common.version import program_name,program_version
import os
import re
from common.dy_import.dy_import import Dynload


def main():
                 
        if len(sys.argv)==1:
                app=dict_app(False)
                #app = dict_app(True,"dict.log")
                app.MainLoop()        
        else:
                current_dict=[]
                for a in os.listdir("modules"):
                        if os.path.isdir("modules/"+a) and os.path.isfile("modules/"+a+"/"+a+".py") :
                                current_dict.append(a)
                has_mp3=False
                output="data.zip"
                input=""
                separate=False
                force=False
                separate_str=""
                argv=sys.argv[1:]   
                if not argv[len(argv)-1].startswith("-"):
                        argv[len(argv)-1]="-!"+argv[len(argv)-1]
                for ma in argv:
                        m=ma.replace("-","")
                        if (m == 'version' and len(ma)==9) or (m=="v" and len(ma)==2):  
                                print program_name()+"  "+program_version()
                        elif (m == 'help'and len(ma)==6) or (m=="h" and len(ma)==2): 
                                print _('''  %s  %s hzh 2013
  This program provides a easy way to look up and download words.Every line of file represents a word.
         usages : python dict.py [Options..] -d="dictionary" file
  Options include:
  -v  --version       : Prints the version number
  -h  --help          : Display this help
  -f  --force         : Force to download, even if there's a file 
                        also named "output"
  -s= --separate=""   : Has separates instead of enter, nothing 
                        means non-Enlish-words
  -m  --mp3           : Download mp3 files as well
  -o= --output-file="": Output file ("./data.zip" is default)
  -d= --dictionary="" : Refer to the dictionary you want to 
                        download if supported''') % (program_name(),program_version())
                        
                        elif (m=="m"and len(ma)==2 ) or (m=="mp3" and len(ma)==5):
                                has_mp3=True
                        
                        elif (m=="f" and len(ma)==2) or (m=="force" and len(ma)==7):
                                force=True
                        
                        elif m.startswith("s=") or m.startswith("separate="):
                                separate=True
                                separate_str=ma[ma.find("=")+1:].replace('"','').replace("'","")
                        
                        elif ma.startswith("-o=") or ma.startswith("--output-file=") :
                                output=ma[ma.find("=")+1:].replace('"','').replace("'","")
                                
                        elif ma.startswith("-d=") or ma.startswith("--dictionary=") :
                                di=ma[ma.find("=")+1:].replace('"','').replace("'","")  
                                if not di in current_dict:
                                        print _("\n**error : dictionary '%s' doesn't exist.**\n")% di
                                        exit(1)
                        
                        elif ma.startswith("-!"):
                                input=ma[2:]
   
                        else:
                                print _('Unknown option %s') % ma
                                sys.exit(1)
                        
                if output!="" and input=="":
                        sys.exit(1)
                
                if input!="":
                        if separate and separate_str=="":
                                pattern=re.compile('''[^a-zA-Z]*([a-zA-Z]*)[^a-zA-Z]*''')
                                a=file(input,"r")
                                match=pattern.findall(a.read())
                                a.close()
                                if match:
                                        for b in range(0,len(match)):
                                                match[b]=match[b]+"\n"
                                        a=file(input,"w")
                                        a.writelines(match)
                                        a.close()
                                else:
                                        print("\n**error:separate string wrong.**\n")
                                        exit(1)
                        if separate and separate_str!="":
                                a=file(input,"r")
                                match=a.read().split(separate_str)
                                a.close()
                                if match:
                                        for b in range(0,len(match)):
                                                match[b]=match[b]+"\n"
                                        a=file(input,"w")
                                        a.writelines(match)
                                        a.close()   
                                else:
                                        print("\n**error:separate string wrong.**\n")
                                        exit(1)
                        append=False
                        if os.path.exists(output) and not force:
                                b=raw_input(_("The file '%s' already exists, override it? Or append to it? <Y/a/n>")%output)
                                print "\n"
                                if b.startswith("y")or b.startswith("Y"):
                                        os.remove(output)
                                elif b.startswith("a")or b.startswith("A"):
                                        #print _("\nFile %s will be appended.\n**The same file will be include twice.**\n") % output 
                                        append=True
                                else:
                                        print _("File %s created failed .")%output
                                        sys.exit(1)
                        try:
                                temp=Dynload("modules.%s.%s" % (di,di),['.'])
                                temp2=temp.getClassInstance("d_"+di)
                                temp.execMethod(temp2,"download",input,output,has_mp3,append)
                        except Exception,e:
                                print "\n**error : import dictionary '%s' failed.**\n" % di
                                sys.exit(1)
                sys.exit(0)

if __name__=="__main__":       
        main()
